package com.szsky.sky.demo;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class AesEncryptUtil_UMC {
    private static String KEY = "btfsmsmy12345678";

    private static String IV = "btfsmsmy12345678";


    public static String encrypt(String data, String key, String iv) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        int blockSize = cipher.getBlockSize();

        byte[] dataBytes = data.getBytes();
        int plaintextLength = dataBytes.length;
        if (plaintextLength % blockSize != 0) {
            plaintextLength += blockSize - plaintextLength % blockSize;
        }

        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

        SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

        cipher.init(1, keyspec, ivspec);
        byte[] encrypted = cipher.doFinal(plaintext);

        return (new Base64()).encodeToString(encrypted);
    }


    public static String desEncrypt(String data, String key, String iv) throws Exception {
        byte[] encrypted1 = (new Base64()).decode(data);

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

        cipher.init(2, keyspec, ivspec);

        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original);
        return originalString;
    }


    public static String encrypt(String data) {
        try {
            return encrypt(data, KEY, IV);
        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }
    }


    public static String decrypt(String data) {
        try {
            return desEncrypt(data, KEY, IV);
        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }
    }


    public static void main(String[] args) throws Exception {
        String data = "abc1234567";
        String key = KEY;
        String iv = IV;

        String encrypt = encrypt(data, key, iv);
        System.out.println("数据：" + data);
        System.out.println("加密后：" + encrypt);
        String decrypt = decrypt(encrypt).trim();
        System.out.println("解密后：" + decrypt);
    }
}
